<?php
namespace app\common\model\user;

use basic\ModelBasic;
use app\common\model as M;

class UserGoldsBill extends ModelBasic
{
   use \traits\ModelTrait;

   // 签到
   const STYPE_SIGN = 1;
   // 购物返
   const STYPE_BUY  = 2;
   // 兑换商品
   const STYPE_EXCHANGE = 3;
   // 登录返
   const STYPE_LOGIN = 4;
   // 邀请注册
   const STYPE_INVITAE_REG = 5;
   // 后台手动赠送
   const STYPE_ADMIN_GIFT = 6;
   /**
    * 类型
    * @var [type]
    */
   public static $stype = [
        1 => '签到',
        2 => '消费返',
        3 => '兑换商品',
        4 => '登录返',
        5 => '邀请注册',
        6 => '后台赠送',
   ];

   /**
     * 设置where条件
     * @Author   FW
     * @DateTime 2021-01-12
     * @Email    123763712@qq.com
     * @param    [type]           $where [description]
     * @param    string           $alias [description]
     * @param    [type]           $model [description]
     */
    public static function setWhere($where,$alias='m',$model=null){
        $model = $model===null ? new self() : $model;

        $model->alias($alias);

        if ( isset($where['stype']) && $where['stype'] > 0 ) {
            $model->where(sprintf('%s.stype=%d' , $alias , $where['stype']));
        }

        // 所属用户full_name活mobile
        if ( isset($where['keyword']) && $where['keyword'] != '' ) {
            $uids = M\User::where("full_name|mobile","LIKE" , '%'.$where['keyword'].'%')->column('uid');
            $model->where($alias.'.uid','IN',$uids);
        }

        if ( isset($where['date_time']) && $where['date_time'] != '' ) {
            $date_time = explode(',',$where['date_time']);
            $model->where($alias.'.create_time' , 'BETWEEN' , [$date_time[0] . ' 00:00:00' , $date_time[1] . ' 23:59:59'] );
        }

        if ( isset($where['create_time']) && $where['create_time'] != '' ) {
            $model->where($alias.'.create_time' , 'LIKE' , '%' . $where['create_time'] . '%');
        }

        if ( isset($where['uid']) && $where['uid'] > 0 ) {
            $model->where(sprintf("%s.uid=%d",$alias,$where['uid']));
        }

        if ( isset($where['order']) && $where['order'] != '' ) {
            $model->order($alias.'.' . $where['order']);
        } else {
            $model->order(sprintf('%s.create_time desc' , $alias));
        }

        return $model;
    }

    /**
     * 列表
     * @Author   FW
     * @DateTime 2020-09-24
     * @Email    123763712@qq.com
     * @param    [type]
     * @return   [type]
     */
    public static function getList($where){
        $count = self::setWhere($where)->count();
        $data  = [];
        if ( $count == 0 ) {
            return compact('data','count');
        }

        $data=self::setWhere($where,'m')
        ->field('m.id,m.amt,m.balance,m.stype,m.remark,m.uid,m.create_time,u.nickname,u.mobile')
        ->join('__USER__ u','m.uid=u.uid')
        ->page($where['page'] ?? 1, $where['limit'] ?? 10)
        ->select();

        if ( !empty($data) ) {
            $data = $data->toArray();
            $data = static::process_list($data);
        }

        return compact('data','count');
    }

    /**
     * 处理列表数据
     * @Author   FW
     * @DateTime 2021-01-12
     * @Email    123763712@qq.com
     * @param    array            $list [description]
     * @return   [type]                 [description]
     */
    public static function process_list (array $list)
    {
        foreach ($list as $key => &$item) {
            $item['stype_display'] = static::$stype[$item['stype']] ?? '-';
        }
        return $list;
    }

   /**
    * 金币账单明细
    * @Author   FW
    * @DateTime 2024-03-15
    * @Email    123763712@qq.com
    * @param    [type]           $amt    发生数量，注意：如果是消费掉的需要自行传入负数
    * @param    [type]           $stype  发生类型：1=签到，2=购物返，3=兑换商品，4=邀请注册
    * @param    [type]           $uid    [description]
    * @param    string           $remark [description]
    */
    public static function add($amt , $stype , $uid, $remark = '')
    {
        if ( !in_array($stype, array_keys(self::$stype) ) ) throw new \Exception('操作失败【G1000】');

        ## 操作用户账户
        $user = M\User::field('golds')->where('uid',$uid)->find();
        $user->golds += $amt;
        if ( $user->golds < 0 ) throw new \Exception('用户金币余额不足');
        $res = $user->save();
        if ($res===false) throw new \Exception('操作失败【G1001】');

        $res = self::create([
            'amt'        => $amt,
            'balance'    => $user->golds,
            'stype'      => $stype,
            'remark'     => $remark ? $remark : sprintf("%s，%s了%d个金币", self::$stype[$stype] ,$amt > 0 ? '增加' : '减少' , abs($amt)),
            'uid'        => $uid,
            'create_time'=> date('Y-m-d H:i:s'),
        ]);
        if ($res===false) throw new \Exception('操作失败【G1002】');

        return true;
    }
} //Class End